package com.sifeng.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @ClassName RandomAmountAlgorithm
 * @Description 总金额随机瓜分功能
 * @Author yang_gsh
 * @Date 2019/7/19 10:55
 */
public class RandomAmountAlgorithm {

    // 最小红包额度
    private static int MINMONEY = 1;

    // 最大红包额度
    private static int MAXMONEY = 10;

    public static void main(String[] args) {
        int money = 2000000;
        int count = 200000;
        int averageValue = money / count;
        System.out.println(averageValue);
        /*MINMONEY = (averageValue - (averageValue - 1)) > 0 ? (averageValue - (averageValue - 1)) : 1;
        MAXMONEY =  (averageValue + (averageValue - 1)) > 0 ? (averageValue + (averageValue - 1)) : 1;
        MAXMONEY = MAXMONEY > 10 ? 10 : MAXMONEY;*/

        System.out.println("平均值：" + averageValue + "-最小值：" + MINMONEY + "-最大值：" + MAXMONEY);

        for (int i = 0; i < 7; i++) {
            List list = splitRedPackets(money, count);

            if (list != null) {
                int amt = 0;
                for (Object o : list) {
                    amt += (Integer) o;
                }
                System.out.println("随机拆分" + money + "拆分" + count + "份：" + list + ":" + amt);
            }
        }
    }

    /**
     * @Description: 随机红包数额（加上minS 为实际金额）
     * @Param: [money, count]
     * @Return: java.util.List<java.lang.Integer>
     */
    private static int random(int money, int count, int minS, int maxS) {

        // 红包数量为1，直接返回金额
        if (count == 1) {
            return money;
        }

        // 每次限定随机数值
        // 首先判断实际最小值
        int realMinS = money - (maxS - minS) * (count - 1);
        int realRange;

        // 如果存在实际最小值，则在实际最小值realMinS 和 maxS-minS 之间 random 数值
        if (realMinS > 0) {
            realRange = maxS - minS - realMinS + 1;
        }

        // 如果不存在实际最小值（也就是说数值可以是minS）
        else {
            if (money > maxS - minS) {
                realMinS  = 0;
                realRange = maxS - minS + 1;
            } else {
                realMinS  = 0;
                realRange = money + 1;
            }
        }

        return new Random().nextInt(realRange) + realMinS;
    }

    /**
     * @Description: 随机拆分红包
     * @Param: [money, count]
     * @Return: java.util.List<java.lang.Integer>
     */
    public static List<Integer> splitRedPackets(int money, int count) {
        if ((money < count * MINMONEY) || (money > count * MAXMONEY)) {
            System.out.println("不可拆分");

            return null;
        }

        // 先预留出 count 份 minS ， 其余的做随机
        int moreMoney = money - count * MINMONEY;
        List<Integer> list      = new ArrayList<Integer>();

        for (int i = 0; i < count; i++) {
            int one = random(moreMoney, count - i, MINMONEY, MAXMONEY);

            list.add(one + MINMONEY);
            moreMoney = moreMoney - one;
        }

        Collections.shuffle(list);

        return list;
    }
}